package com.chenyue.cm.api.live;

import com.chenyue.cm.auth.Login;
import com.chenyue.cm.auth.LoginUser;
import com.chenyue.cm.bean.Success;
import com.chenyue.cm.common.constant.ErrorCode;
import com.chenyue.cm.match.domain.JdMatchAppointment;
import com.chenyue.cm.match.service.JdMatchAppointmentService;
import com.chenyue.cm.user.domain.JdAppUser;
import com.chenyue.cm.utils.DateUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

/**
 * @author libingxing
 */
@Api(tags = "直播预约")
@RestController
@RequestMapping("/api/appointment")
public class ApiLiveAppointmentController {

    private final JdMatchAppointmentService matchAppointmentService;

    public ApiLiveAppointmentController(JdMatchAppointmentService matchAppointmentService) {
        this.matchAppointmentService = matchAppointmentService;
    }

    @Login
    @PostMapping("/appointment")
    @ApiOperation("预约赛事直播")
    public Success<String> appointment(
            @ApiIgnore @LoginUser JdAppUser user,
            @ApiParam JdMatchAppointment appointment
    ) {
        final JdMatchAppointment one = matchAppointmentService.lambdaQuery()
                .eq(JdMatchAppointment::getLiveRecordId, appointment.getLiveRecordId())
                .eq(JdMatchAppointment::getUserId, user.getId()).one();
        if (one == null) {
            appointment.setCt(DateUtils.getToday());
            appointment.setUserId(Integer.valueOf(user.getId()));
            final boolean save = matchAppointmentService.save(appointment);
            return save ? Success.success() : Success.error(ErrorCode.INSERT_ERROR.getMsg());
        } else {
            matchAppointmentService.deleteByPrimaryKey(one.getId() + "");
            return Success.success();
        }
    }

}
